package com.yantong.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片处理
 *
 * @author liaozhaogui-773104632@qq.com
 * @date 2020/11/26 11:20
 */
public class QRCodeUtil {

//	public static void main(String[] args) throws Exception {
//		referrerEncode("嘻嘻","https://down.yantongtech.cn/data/upload/images/2021-03-12/b6b353e91ff33c9300ccd11074ae50bb.png");
//	}

	/**
	 * 生成邀请推荐分享图
	 *
	 * @param content
	 * @param sourcePath
	 * @throws Exception
	 */
	public static BufferedImage referrerEncode(Color color ,String content, String sourcePath) throws Exception {
		// 构造URL
		URL url = new URL(sourcePath);
		// 打开连接
		URLConnection con = url.openConnection();
		//设置请求超时为5s
		con.setConnectTimeout(5 * 1000);
		// 输入流
		InputStream is = con.getInputStream();
		BufferedImage image = ImageIO.read(is);

		Path path = FileSystems.getDefault().getPath("font", "yuanti.ttc");
		Font font = Font.createFont(Font.TRUETYPE_FONT, new File(path.toUri())).deriveFont(Font.BOLD, 30);
		try {
			Graphics2D graphics2d = image.createGraphics();
			graphics2d.setFont(font);
			graphics2d.setColor(color);
			//消除文字锯齿
			graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			//消除图像锯齿
			graphics2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

			FontMetrics fontMetrics = graphics2d.getFontMetrics(font);
			// 计算出中心点 x 位置
			int centerX = image.getWidth();
			// 计算出中心点 y 位置
			int centerY = image.getHeight() / 4 + 12;
			// 文字宽度
			int textWidth = fontMetrics.stringWidth(content);
			// 计算出中心点，并且绘制出文字
			graphics2d.drawString(content, centerX - textWidth - (centerX / 5) +25, centerY);
			// 保存
			graphics2d.dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
		//存储本地
		//ImageIO.write(image, "PNG", new File("D:/Software/Cache/Download/8910.png"));
		return image;
	}

	/**
	 * @param url               跳转路径
	 * @param agentQrCodeWidth  二维码宽
	 * @param agentQrCodeHeight 二维码高
	 */
	public static BufferedImage getQrCode(String url, Integer agentQrCodeWidth, Integer agentQrCodeHeight) {
		BufferedImage image = null;
		try {
			MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
			Map<EncodeHintType, Object> hints = new HashMap<>(16);
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			//控制二维码白边宽度
			hints.put(EncodeHintType.MARGIN, 0);
			// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
			BitMatrix bitMatrix = multiFormatWriter.encode(url, BarcodeFormat.QR_CODE, agentQrCodeWidth, agentQrCodeHeight, hints);
			bitMatrix = deleteWhite(bitMatrix);
			// 生成二维码
			image = MatrixToImageWriter.toBufferedImage(bitMatrix);
			Graphics2D g = image.createGraphics();
			g.dispose();
			image.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return image;
	}

	/**
	 * 删除白边
	 * */

	private static BitMatrix deleteWhite(BitMatrix matrix) {
		int[] rec = matrix.getEnclosingRectangle();
		int resWidth = rec[2] + 1;
		int resHeight = rec[3] + 1;

		BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
		resMatrix.clear();
		for (int i = 0; i < resWidth; i++) {
			for (int j = 0; j < resHeight; j++) {
				if (matrix.get(i + rec[0], j + rec[1])) {
					resMatrix.set(i, j);
				}
			}
		}
		return resMatrix;
	}
}
